import React, { useState, useRef, useEffect, lazy, Suspense, useMemo } from 'react'
import { message, Input, DatePicker, Button, Form } from 'antd'
import bus from '../../../../utils/eventBus';
import { DownloadOutlined } from '@ant-design/icons'
import { useSelector } from 'react-redux'
import { paperSizeOptions, printTypeOptions, colorOptions, secretOptions } from "../../../../utils/constant";
import LdPrintTable from '../../../../components/LdPrintTable'
import './index.scss'
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { current } from '@reduxjs/toolkit';
dayjs.extend(customParseFormat);
interface pageConfigType {
    currentPage: number,
    total: number,
    pageSize: number
}
const DetailView = lazy(() => import('./DetailView'))
const History = () => {
    const { id = '', permission = 0 } = useSelector((state: any) => state.userReducer.userInfo)
    const detailRow = useRef<any>(undefined)
    const multipleSelection = useRef<any[]>([])
    const formRef = useRef<any>(null)
    const [showDetail, setShowDetail] = useState<boolean>(false)
    const [tableData, setTableData] = useState<any[]>([])
    const config = useRef<pageConfigType>({
        currentPage: 1,
        total: 0,
        pageSize: 10
    })
    const columns = useRef([
        { key: "fileTitle", dataIndex: 'fileTitle', title: "标题" },
        { key: 'fileLevelLable', dataIndex: "fileLevelLable", title: "密级", width: 55 },
        { key: 'page', dataIndex: 'page', title: '页数', width: 55 },
        { key: "part", dataIndex: "part", title: '份数', width: 55 },
        { key: 'statusLabel', dataIndex: 'statusLabel', title: '打印状态', width: 80 },
        { key: "fileFinishTime", dataIndex: 'fileFinishTime', title: '完成时间', width: 150 },
        {
            key: 'action',
            dataIndex: "action",
            title: '操作',
            width: 55,
            render: (_: any, record: any) => {
                return (
                    <Button style={{ padding: 0 }} type="link" onClick={() => handleViewDetail(record)}>详情</Button>
                )
            }
        }
    ])
    const showUserMine = useMemo(() => {
        return ![0, 4, 5, 6].includes(permission);
    }, [permission])
    const disabledStartDate = (time: any) => {
        const { endDate } = formRef.current.getFieldValue()
        if (endDate) {
            return time && time > new Date(endDate).getTime();
        }
    };
    const disabledEndDate = (time: any) => {
        const { startDate } = formRef.current.getFieldValue()
        if (startDate) {
            return time && time < new Date(startDate).getTime();
        }
    };
    const handlePage = (page: pageConfigType) => {
        config.current = page
        loadData()
    }
    const handleViewDetail = (row: any) => {
        detailRow.current = { ...row }
        setShowDetail(true)
    }
    const handleExport = () => {
        const { keyword = '', startDate = '', endDate = '' } = formRef.current.getFieldValue()
        const data = {
            data: multipleSelection.current,
            keyword,
            endDate: endDate ? `${endDate.format('YYYY-MM-DD')} 23:59:59` : "",
            startDate: startDate ? `${startDate.format('YYYY-MM-DD')} 00:00:00` : "",
        }
        window.chromePro.exportPrintLog(
            JSON.stringify(data)
        );
    }
    const exportPrintLogFinished = (data: any) => {
        if (data.code === 200) {
            message.success(data.msg);
        } else {
            message.error(data.msg);
        }
    }
    const getPrintRecordFinished = (data: any) => {
        console.log(data,'data')
        if (data.code === 200) {
            const tableData = data.data.map((item: any) => {
                return {
                    ...item,
                    statusLabel: item.status == 1 ? "成功" : item.status == 2 ? "打印中" : "失败",
                    printLayerText: printTypeOptions.find((res) => res.value === item.printLayer)?.label,
                    pageSizeText: paperSizeOptions.find((res) => res.value === item.pageSize)?.label,
                    printColorText: colorOptions.find((res) => res.value === item.printColor)?.label,
                    fileLevelLable: secretOptions.find((res) => res.value === item.fileLevel)?.label,
                };
            });
            setTableData(tableData)
            config.current = {...config.current,total: data.total}
        } else {
            message.error(data.msg);
        }
    }
    const formChange = (changeValue: any, allValue: any) => {
        if (changeValue.keyword) return
        config.current = {...config.current,currentPage:1}
        loadData()
    }
    const handleSearch = (e: any) => {
        if (e.key === 'Enter') {
            config.current = {...config.current,currentPage:1}
            loadData()
        }
    }
    const loadData = () => {
        const { keyword = '', startDate = '', endDate = '' } = formRef.current.getFieldsValue()
        const data = {
            ...config.current,
            keyword,
            endDate: endDate ? `${endDate.format('YYYY-MM-DD')} 23:59:59` : "",
            startDate: startDate ? `${startDate.format('YYYY-MM-DD')} 00:00:00` : "",
            responsible: id,
        }
        console.log(data, 'data')
        window.chromePro.getPrintRecord(
            JSON.stringify(data)
        );
    }
    const onClose = () => {
        setShowDetail(false)
    }
    const selectRowChange = (val: any[]) => {
        multipleSelection.current = [...val]
    }
    useEffect(() => {
        bus.addListener("exportPrintLogFinished", exportPrintLogFinished);
        bus.addListener("getPrintRecordFinished", getPrintRecordFinished);
        loadData();
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener("exportPrintLogFinished", exportPrintLogFinished);
            bus.removeListener("getPrintRecordFinished", getPrintRecordFinished);
        }
    }, [])
    return (
        <>
            <div className="h100 w100">
                {
                    !showUserMine ?
                        <>
                            <div className="filter flex-between mb-10">
                                <Form layout='inline' ref={formRef} onValuesChange={formChange}>
                                    <Form.Item name='keyword'>
                                        <Input className="custom-input" onKeyUp={handleSearch}
                                            style={{ width: "240px" }} placeholder="请输入关键字回车检索"></Input>
                                    </Form.Item>
                                    <Form.Item name='startDate'>
                                        <DatePicker format="YYYY-MM-DD"
                                            placeholder="选择开始日期"
                                            disabledDate={disabledStartDate}
                                            style={{ margin: '0 10px', width: '140px' }}></DatePicker>
                                    </Form.Item>
                                    <Form.Item name='endDate'>
                                        <DatePicker format="YYYY-MM-DD"
                                            placeholder="选择结束日期"
                                            disabledDate={disabledEndDate}
                                            style={{ width: '140px' }}></DatePicker>
                                    </Form.Item>

                                </Form>
                                <Button onClick={handleExport} type="primary" icon={<DownloadOutlined />} >导出</Button>
                            </div>
                            <div style={{ height: 'calc(100% - 42px)' }}>
                                <LdPrintTable selectRowChange={selectRowChange} handlePage={handlePage} data={tableData} columns={columns.current} pageConfig={config.current} tableHeight="calc(100% - 38px)">
                                </LdPrintTable>
                            </div>
                        </>
                        : <div className="empty-content flex-center align-center">
                            <div>
                                <img draggable={false} src="../../../../assets/task/empty.png" width="156px" />
                                <div style={{ width: '100%', textAlign: 'center', color: 'rgba(137, 147, 154, 100)', fontSize: '14px' }}
                                    className="mt-10">
                                    暂无任务队列
                                </div>
                            </div>
                        </div>
                }
            </div>
            <Suspense>
                {
                    showDetail ? <DetailView onClose={onClose} detail={detailRow.current} /> : null
                }
            </Suspense>
        </>
    )
}
export default History